//
//  MonitoringViewController.m
//  ZhangJiangJun
//
//  Created by FENGYL on 2017/1/17.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "MonitoringViewController.h"
#import "NetworkCommand.h"
#import "MonitoringTableViewCell.h"
#import "UserModel.h"
#import "HistoryCalendarViewController.h"
#import "KCAnnotation.h"
#import "WGS84TOGCJ02.h"
#import "UIView+XL.h"

#import <MJRefresh.h>
#import <MBProgressHUD.h>
#import <MapKit/MapKit.h>

static NSString * cellIdentifier = @"TimeLineCell";

@interface MonitoringViewController ()<UITableViewDelegate,UITableViewDataSource,MKMapViewDelegate>

@property (weak, nonatomic) IBOutlet UIBarButtonItem *historyBarButtonItem;
@property (weak, nonatomic) IBOutlet UIButton *monitoringRecordButton;
@property (weak, nonatomic) IBOutlet UITableView *timeLineTableView;

@property (strong, nonatomic) UserModel * userModel;
@property (strong, nonatomic) MKMapView * mapView;
@property (strong , nonatomic) CLLocationManager * locationManager;
@property (strong, nonatomic) NSMutableArray * validAlarmArray;

@end

@implementation MonitoringViewController

-(NSMutableArray *)validAlarmArray{
    
    if (!_validAlarmArray) {
        
        _validAlarmArray = [NSMutableArray array];
        
        for (NSDictionary * dict in _userModel.deviceHistoryEventDataByTimeArray) {
            
            NSNumber * alarmType = [dict valueForKey:NC_ALARM_TYPE];
            
            if (!([alarmType isEqual:@12] || [alarmType isEqual:@13] || [alarmType isEqual:@21])) {
                
                [_validAlarmArray addObject:dict];
                
            }
            
        }
        
    }
    return _validAlarmArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
    self.timeLineTableView.delegate = self;
    self.timeLineTableView.dataSource = self;
    
}

-(void)setUpUI{
    
    //cell自适应高度
    self.timeLineTableView.estimatedRowHeight = 61;
    self.timeLineTableView.rowHeight = UITableViewAutomaticDimension;
    
    //UserModel
    self.userModel = [[UserModel alloc]init];
    
    //历史按钮
    [self.historyBarButtonItem setTitle:NSLocalizedString(LOCALIZABLE_HISTORY, nil)];
    
    //监控记录label
    [self.monitoringRecordButton setTitle:NSLocalizedString(LOCALIZABLE_MONITORING_RECORD, nil) forState:UIControlStateNormal];
    
    //获取时间轴
    [self getAlertList:[NSDate date]];
    
    
    //判断权限
    [self locationEnable];
    
    //地图
    [self setMap];
    
    //加载数据
    [self loadAlertLocation:[NSDate date]];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 获取警报
-(void)getAlertList:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *stringDate = [dateFormatter stringFromDate:date];
    
    [self setTitle:stringDate];
    
    //获取时间轴
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [hud.label setText:NSLocalizedString(LOCALIZABLE_LOADING, nil)];
    
    hud.mode = MBProgressHUDModeIndeterminate;
    
    hud.removeFromSuperViewOnHide = YES;
    
    [NetworkCommand getHistoryEventDataByTime:date success:^{
        
        [self.timeLineTableView reloadData];
        
        [hud hideAnimated:YES];
        
    } failure:^{
        
        [hud.label setText:NSLocalizedString(LOCALIZABLE_REFRESHING_FAILED, nil)];
        
        hud.mode = MBProgressHUDModeCustomView;
        
        [hud hideAnimated:YES afterDelay:0.5];
        
    }];
    
}

#pragma mark 选择日期
- (IBAction)historySelect:(id)sender {
    
    HistoryCalendarViewController * historyCalendarViewController = [[HistoryCalendarViewController alloc]init];
    
    [self showViewController:historyCalendarViewController sender:nil];
    
}

#pragma mark TableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.validAlarmArray.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dict = self.validAlarmArray[indexPath.row];
    
    MonitoringTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        
        cell = [[MonitoringTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    //点击不变色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    NSString * timeStamp = [NSString stringWithFormat:@"%@",[dict valueForKey:NC_EVENT_TIME]];
    
    NSNumber *alarmType = [dict valueForKey:NC_ALARM_TYPE];
    
    NSString * message = [dict valueForKey:NC_MESSAGE];
    
    NSLog(@"message %@",message);
    
    if ([message isEqualToString:@""] || [message isEqualToString:@"null"]) {
        
        message = nil;
        
    }
    
    [cell setTime:[NetworkCommand TimestampChangeTimestr:timeStamp] alarmType:alarmType message:message];
    
    return cell;
    
}

#pragma mark reload数据
-(void)reloadValidAlarmArray{
    
    _validAlarmArray = nil;
    
}

#pragma mark 初始化地图

-(void)setMap{
    
    self.mapView = [[MKMapView alloc]initWithFrame:self.timeLineTableView.frame];
    
    self.mapView.height = [UIScreen mainScreen].bounds.size.height - 125;
    
    [self.view addSubview:self.mapView];
    
    [self.view sendSubviewToBack:self.mapView];
    
    self.mapView.delegate = self;
    
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    self.mapView.mapType = MKMapTypeStandard;
    
    
    
    
}

#pragma mark 加载报警地点
-(void)loadAlertLocation:(NSDate *)date{
    
    [_mapView removeAnnotations:_mapView.annotations];
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [hud.label setText:NSLocalizedString(LOCALIZABLE_LOADING, nil)];
    
    hud.mode = MBProgressHUDModeIndeterminate;
    
    hud.removeFromSuperViewOnHide = YES;
    
    
    
    [NetworkCommand getDeviceLocationByTime:date Success:^{
        
        
        for (NSDictionary * dict in self.userModel.deviceHistoryEventLocationByTimeArray) {
            
            NSNumber *latitude = [dict valueForKey:NC_LAT];
            
            NSNumber *longitude = [dict valueForKey:NC_LNG];
            
            [self addAnnotationForLatitude:[latitude doubleValue] longitude:[longitude doubleValue]];
            
        }
        
        [hud hideAnimated:YES];
        
        
    } failure:^{
        
        [hud.label setText:NSLocalizedString(LOCALIZABLE_REFRESHING_FAILED, nil)];
        
        hud.mode = MBProgressHUDModeCustomView;
        
        [hud hideAnimated:YES afterDelay:0.5];
        
    }];
    
}

#pragma mark 判断是否有权限
-(void)locationEnable{
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    //是否具有定位权限
    int status=[CLLocationManager authorizationStatus];
    
    //请求权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8)
    {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
    }
    
    if (status < 3){
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"用户未允许开启定位服务" message:@"请手动开启定位" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
                
            }
            
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        
        
    }
    
}

#pragma mark 添加大头针
-(void)addAnnotationForLatitude:(double)latitude longitude:(double)longitude{
    
    
    
    CLLocationCoordinate2D location = CLLocationCoordinate2DMake(latitude, longitude);
    
    KCAnnotation *annotation = [[KCAnnotation alloc]init];
    annotation.coordinate = location;
    annotation.image = [UIImage imageNamed:@"zjj_i_icon"];
    
    //偏移
    if (![WGS84TOGCJ02 isLocationOutOfChina:location]) {
        //转换后的coord
        CLLocationCoordinate2D newLocation = [WGS84TOGCJ02 transformFromWGSToGCJ2:location];
        
        annotation.coordinate = newLocation;
        
    }
    
    
    [_mapView addAnnotation:annotation];
    
}

#pragma mark 切换地图和时间轴
- (IBAction)mapOrTimeLineChange:(id)sender {
    
    self.mapView.hidden = !self.mapView.hidden;
    self.timeLineTableView.hidden = !self.timeLineTableView.hidden;
    
    if (!self.mapView.hidden && self.timeLineTableView.hidden) {
        
        [self.monitoringRecordButton setTitle:NSLocalizedString(LOCALIZABLE_MONITORING_RECORD, nil) forState:UIControlStateNormal];
        
    }else{
        
        [self.monitoringRecordButton setTitle:NSLocalizedString(LOCALIZABLE_MAP, nil) forState:UIControlStateNormal];
        
        
    }
    
}

#pragma mark - 地图控件代理方法
#pragma mark 显示大头针时调用，注意方法中的annotation参数是即将显示的大头针对象
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1 = @"AnnotationKey1";
        MKAnnotationView *annotationView = [_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout = NO;//允许交互点击
//            annotationView.calloutOffset = CGPointMake(0, 1);//定义详情视图偏移量
            annotationView.leftCalloutAccessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"zjj_i_icon"]];//定义详情左侧视图
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation = annotation;
        annotationView.image = ((KCAnnotation *)annotation).image;//设置大头针视图的图片
        
        return annotationView;
    }else {
        return nil;
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
